package com.zh.mp.demo.modules.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zh.mp.demo.modules.goods.entity.Stock;
import com.zh.mp.demo.modules.goods.mapper.StockMapper;
import com.zh.mp.demo.modules.goods.service.IStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.mp.demo.modules.order.entity.OrderDto;
import com.zh.mp.demo.modules.order.entity.Orders;
import com.zh.mp.demo.modules.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 商品库存 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-03-20
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {
    @Autowired
    private IOrderService iOrderService;

    /**
     * 更新库存
     * @param orderDto
     */
    @Override
    //@Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void updateStock(OrderDto orderDto) {
        //校验商品以及库存
        Stock stock = this.baseMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getGoodsCode,orderDto.getGoodsCode()));
        if (stock == null) {
            throw new RuntimeException("暂未查询到该库存");
        } else if (stock.getStockNum().compareTo(orderDto.getOrderNumber())<0) {
            throw new RuntimeException("商品"+stock.getGoodsName()+"库存不足");
        }
        this.baseMapper.update(null,new UpdateWrapper<Stock>()
                .setSql("stock_num=stock_num-"+orderDto.getOrderNumber())
                .eq("goods_code",orderDto.getGoodsCode())
        );
        //再次查询库存看 是否有负库存
        Stock stockT = this.baseMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getGoodsCode,orderDto.getGoodsCode()));
        if (stockT.getStockNum().compareTo(0)<0) {
            throw new RuntimeException("库存扣减为负数，订单失败");
        }
        Orders orders = this.iOrderService.getOne(new LambdaQueryWrapper<Orders>().eq(Orders::getOrderCode,orderDto.getOrderCode()));
        System.out.println("扣减库存下查询到订单:"+ orders);


    }
}
